package middleware

import (
	"bp/internal/util"
	"context"
	"encoding/json"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
)

func injectAuthorizationToken(ctx context.Context, md metadata.MD) context.Context {
	var tokenStr string
	
	tokenValues := md.Get("atoken")
	if len(tokenValues) > 0 {
		tokenStr = tokenValues[0]
	}

	if util.IsEmpty(tokenStr) {
		return ctx
	}

	tokenPtr := &util.AuthorizationToken{}
	err := json.Unmarshal([]byte(tokenStr), tokenPtr)
	if err != nil {
		return ctx
	}
	return context.WithValue(ctx, util.AuthorizationTokenKey{}, tokenPtr)
}

// UnaryAuthorizationTokenInterceptor add authorization token
func UnaryAuthorizationTokenInterceptor(slog *zap.SugaredLogger, decider util.ServerInterceptorDecider) grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
		if decider(ctx, info.FullMethod, info.Server) {
			md, ok := metadata.FromIncomingContext(ctx)
			if ok {
				ctx = injectAuthorizationToken(ctx, md)
			}
		}
		return handler(ctx, req)
	}
}
